package com.lottery.game.runner.v2.trigger;

import com.alibaba.fastjson.JSONObject;
import com.lottery.game.common.constants.GameConstants;
import com.lottery.game.core.modules.entity.game.GameRoom;
import com.lottery.game.core.modules.service.app.BetService;
import com.lottery.game.core.modules.service.app.OnlineAppContext;
import com.lottery.game.core.modules.service.app.WebSocketService;
import com.lottery.game.core.modules.service.app.WebsocketMessageService;
import com.lottery.game.runner.v2.GamblingClosuresExecutor;
import com.lottery.game.runner.v2.RoomDetail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class RoomOfflineTrigger {

	@Autowired
	private BetService betService;

	@Autowired
	private WebSocketService webSocketService;

	@Autowired
	private OnlineAppContext onlineAppContext;

	@Autowired
	private WebsocketMessageService websocketMessageService;

	public void apply(RoomDetail roomDetail, GameRoom gameRoom) {
		// 获取正在运行房间
		Map<String, String> map = new HashMap<String, String>();
		map.put("expect", roomDetail.getExpect());
		map.put("status", "-2");
		map.put("content", "系统维护,大约" + (roomDetail.getDownTime() / 60) + "分钟");
		map.put("time", String.valueOf((roomDetail.getDownTime() / 60)));
		String roomLotteryTicketType = gameRoom.getRoomLotteryTicketType();
		if(roomLotteryTicketType!=null) {
			List<GameRoom> roomList = betService.queryRoomList(gameRoom);
			GamblingClosuresExecutor executor = new GamblingClosuresExecutor(webSocketService, onlineAppContext);
			executor.initParams(roomList, JSONObject.toJSONString(map), websocketMessageService, GameConstants.GAME_STATUS_MAINTAIN);
			executor.execute();
		}

		log.info("游戏类型【{}】， 停机维护时间准备【{}】睡眠分钟。。。", roomDetail.getBetType(), (roomDetail.getDownTime() / 60));
 
		try {
			TimeUnit.SECONDS.sleep(roomDetail.getDownTime());
		} catch (InterruptedException e) {
			log.error(e.getMessage(), e);
		}
	}

}
